package spring.security.core.jackson;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

public class ReturnValueHandlerSupport implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof RequestMappingHandlerAdapter) {
			List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(((RequestMappingHandlerAdapter) bean).getReturnValueHandlers());
			JsonReturnValueHandler jsonHandler = null;

			for (int adapter = 0; adapter < handlers.size(); ++adapter) {
				HandlerMethodReturnValueHandler handler = (HandlerMethodReturnValueHandler) handlers.get(adapter);
				if (handler instanceof JsonReturnValueHandler) {
					jsonHandler = (JsonReturnValueHandler) handler;
					break;
				}
			}

			if (jsonHandler != null) {
				handlers.remove(jsonHandler);
				handlers.add(0, jsonHandler);
				RequestMappingHandlerAdapter arg6 = (RequestMappingHandlerAdapter) bean;
				arg6.setReturnValueHandlers(handlers);
			}
		}

		return bean;
	}

}
